/*
 * @Author: 
 * @Date: 2025-06-11 14:15:20
 * @LastEditTime: 2025-08-21 12:14:04
 * @Description: 
 */
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../system/fontsize_provider.dart'; // 根据实际路径调整

class BinAssignmentScreen extends StatefulWidget {
  const BinAssignmentScreen({super.key});

  @override
  _BinAssignmentScreenState createState() => _BinAssignmentScreenState();
}

class _BinAssignmentScreenState extends State<BinAssignmentScreen> {
  final List<String> orders = [
    'HD-00121391201291',
    'WF-129381223FD',
    'HD-00121396201291',
    'WF-129321293FD',
    'HD-0012151201291',
    'WF-129281293FD',
    'HD-0012191201291',
    'WF-129391293FD',
    'HD-00144391201291',
    'WF-127881293FD',
  ];

  String? selectedOrder;
  final TextEditingController binController = TextEditingController();
  final FocusNode binFocusNode = FocusNode();
  String combinedValue = '';
  
  double baseFontSize = 13;
  double listFontSize = 12;
  late double _fontScale;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(binFocusNode);
    });
  }

  @override
  void dispose() {
    binController.dispose();
    binFocusNode.dispose();
    super.dispose();
  }

  void updateCombinedValue() {
    setState(() {
      combinedValue = selectedOrder != null && binController.text.isNotEmpty
          ? '$selectedOrder | ${binController.text}'
          : '';
    });
  }

  void _handleOrderSelection(String orderItem) {
    setState(() {
      if (selectedOrder == orderItem) {
        selectedOrder = null;
      } else {
        selectedOrder = orderItem;
      }
      updateCombinedValue();
    });
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;

    return Scaffold(
      appBar: AppBar(
        title: const Text('Bin Assignment'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () => Navigator.pushNamed(context, '/home'),
          ),
        ],
        backgroundColor: const Color(0xFF008363)
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        behavior: HitTestBehavior.opaque,
        child: Padding(
          padding: const EdgeInsets.all(32),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Orders:', 
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: baseFontSize * _fontScale
                )
              ),
              const SizedBox(height: 8),
              Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(4),
                ),
                height: 150,
                child: ListView.builder(
                  itemCount: orders.length,
                  itemBuilder: (context, index) {
                    final order = orders[index];
                    return ListTile(
                      title: Text(
                        order,
                        style: TextStyle(
                          fontSize: listFontSize * _fontScale,
                          fontWeight: FontWeight.bold,
                          color: selectedOrder == order ? Colors.green : Colors.black,
                        ),
                      ),
                      tileColor: selectedOrder == order ? Colors.green[50] : null,
                      onTap: () => _handleOrderSelection(order),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 16),
                    );
                  },
                ),
              ),
              const SizedBox(height: 16),
              Text(
                'Order:', 
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: baseFontSize * _fontScale
                )
              ),
              SizedBox(
                height: 30,
                child: TextFormField(
                  readOnly: true,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    hintText: 'Select an order above',
                    contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 10)
                  ),
                  controller: TextEditingController(text: selectedOrder),
                  style: TextStyle(fontSize: baseFontSize * _fontScale),
                ),
              ),
              const SizedBox(height: 16),
              Text(
                'BIN:', 
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: baseFontSize * _fontScale
                )
              ),
              SizedBox(
                height: 30,
                child:TextFormField(
                  focusNode: binFocusNode,
                  controller: binController,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    hintText: 'Scan or enter BIN',
                    contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 0)
                  ),
                  onChanged: (value) => updateCombinedValue(),
                  style: TextStyle(fontSize: baseFontSize * _fontScale),
                ),
              ),
              const SizedBox(height: 16),
              Text(
                'Order | BIN:', 
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: baseFontSize * _fontScale
                )
              ),
              SizedBox(
                height: 30,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                  width: double.infinity,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    combinedValue, 
                    style: TextStyle(
                      fontSize: baseFontSize * _fontScale
                    )
                  ),
                ),
              ),
              const SizedBox(height: 20),
              SizedBox(
                width: double.infinity,
                child:ElevatedButton(
                  onPressed: () {},
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF008363),
                    padding: const EdgeInsets.symmetric(vertical: 10),
                  ),
                  child: const Text('OK', style: TextStyle(color: Colors.white)),
                ),
              ),
              const SizedBox(height: 10),
              SizedBox(
                width: double.infinity,
                child:ElevatedButton(
                  onPressed: () {},
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF008363),
                    padding: const EdgeInsets.symmetric(vertical: 10),
                  ),
                  child: const Text('Rollback', style: TextStyle(color: Colors.white)),
                ),
              ),
              const SizedBox(height: 10),
              SizedBox(
                width: double.infinity,
                child:ElevatedButton.icon(
                  onPressed: () {
                    // ########## 核心修改：添加 source 字段标识来源页面 ##########
                    Navigator.pushNamed(
                      context,
                      '/picking/picking',
                      arguments: {
                        'waveId': '',
                        'source': 'binAssignment' // 标识从 BinAssignmentScreen 跳转
                      },
                    );
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF008363),
                    padding: const EdgeInsets.symmetric(vertical: 10),
                  ),
                  label: const Text('Start Picking', style: TextStyle(color: Colors.white)),
                  icon: const Icon(Icons.start, color: Colors.white),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}